package cn.com.gridinfo.sooc.core.my.course.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jeremy.arad.utils.AnimUtil;
import com.jeremy.arad.utils.Log;
import com.jeremy.arad.utils.StringUtils;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerviewViewHolder;
import com.marshalchen.ultimaterecyclerview.UltimateViewAdapter;
import com.squareup.picasso.Picasso;

import java.util.List;

import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.http.SoocNetResult;
import cn.com.gridinfo.sooc.core.course.classes.activity.CourseDetailActivity;
import cn.com.gridinfo.sooc.core.course.note.common.CodeConst;
import cn.com.gridinfo.sooc.core.course.note.dao.CourseDao;
import cn.com.gridinfo.sooc.core.my.course.bean.JRCourse;
import cn.com.gridinfo.sooc.utils.DateUtil;
import cn.com.gridinfo.sooc.utils.MessageUtils;
import cn.com.gridinfo.sooc.utils.TypeConvert;

/**
 * 已加入课程 适配器
 * Created by 刘晓晨 on 2015/12/10.
 */
public class JRCourseAdapter extends UltimateViewAdapter<JRCourseAdapter.ViewHolder> implements SoocNetResult {
    Context context;
    private List<JRCourse> courseList;
    private ViewHolder viewHolder;
    private View viewDilag;//评价对话框布局
    private RatingBar ratingBar;//评价对话框的星级
    private CourseDao dao;
    private int pjPostion = -1;//点击评价的列表项
    private TextView tvPf;//评分

    public JRCourseAdapter(List<JRCourse> list, Context context) {
        this.context = context;
        this.courseList = list;
        dao = new CourseDao(this);
    }

    @Override
    public ViewHolder getViewHolder(View view) {
        return new ViewHolder(view, false);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent) {
        //加载布局
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_jr_course, parent, false);

        return new ViewHolder(view, true);
    }

    @Override
    public int getAdapterItemCount() {
        return courseList.size();
    }

    @Override
    public long generateHeaderId(int position) {
        return position;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        if (position < getItemCount() && (customHeaderView != null ?
                position <= courseList.size() : position < courseList.size()) &&
                (customHeaderView != null ? position > 0 : true)) {
            final JRCourse jrCourse = courseList.get(position);
            //加载课程封面
            Picasso.with(context).load(jrCourse.getKcfm()).resize(context.getResources().getDimensionPixelSize(R.dimen.fengmian_width_in_mine),
                    context.getResources().getDimensionPixelSize(R.dimen.fengmian_height_in_mine)).placeholder(R.mipmap.course_placeholder)
                    .error(R.mipmap.course_placeholder).into(holder.kcfm);

            holder.kcmc.setText(jrCourse.getKcmc());
            //加载更新时间，没有的话显示 无
            if (StringUtils.isNull(jrCourse.getUpdate_time()) || jrCourse.getUpdate_time().equals("0")) {
                holder.updateTime.setText("上次学习 无");
            } else {
                holder.updateTime.setText("上次学习" + DateUtil.getDateFromDatestamp(jrCourse.getUpdate_time()));
            }
            if(jrCourse.getIsJudge() == 0){
                //未评价，显示评价按钮
                holder.pj.setVisibility(View.VISIBLE);
            }else{
                //已评价，隐藏评价按钮
                holder.pj.setVisibility(View.INVISIBLE);
            }
            //显示课程进展 无的话设置为0
//            if (StringUtils.isNull(jrCourse.getKcjz() + "")) {
//                holder.progressBar.setProgress(0);
//            } else {
//                holder.progressBar.setProgress(jrCourse.getKcjz());
//            }
//            holder.kczs.setText(jrCourse.getKczs());//课程总的章节数量
            holder.kcjd.setText("已学" + jrCourse.getKcjd() + "/" + jrCourse.getKczs() + "课");//课程目前学习进度：目前学了的章节数
            holder.ao.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, CourseDetailActivity.class);
                    intent.putExtra("kcid", jrCourse.getKcid());
                    intent.putExtra("kcfm",jrCourse.getKcfm());
                    context.startActivity(intent);
                    AnimUtil.intentSlidIn((Activity) context);//加动画
                }
            });
            //底部分割线的显示
            if (position == (courseList.size() - 1)) {
                holder.line.setVisibility(View.VISIBLE);
            } else {
                holder.line.setVisibility(View.GONE);
            }

            holder.pj.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //是否学习超过了80%
                    pjPostion = position;
                    goJudge(jrCourse.getKcid());
                }
            });
        }

    }

    /**
     * 初始化评价对话框的布局
     */
    void initDialogView() {
        viewDilag = LayoutInflater.from(context).inflate(R.layout.course_judge, null);
        ratingBar = (RatingBar) viewDilag.findViewById(R.id.judge);
        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                if(rating>0){
                    tvPf.setText(rating+"分");
                }
            }
        });
        tvPf = (TextView) viewDilag.findViewById(R.id.tip);
        tvPf.setText("未评分");
    }

    /**
     * 去评价
     */
    void goJudge(final String kcid) {
        initDialogView();
        ratingBar.setEnabled(true);
        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                if(rating>0){
                    tvPf.setText(TypeConvert.floatToInt(rating)+"分");
                }
            }
        });
        new MaterialDialog.Builder(context)
                .backgroundColor(Color.WHITE)
                .titleColorRes(R.color.color_tv333)
                .customView(viewDilag, true)
                .positiveText(R.string.agree)
                .positiveColorRes(R.color.colorAccent)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                        //提交课程评价
                        Log.d("kcid=" + kcid);
                        Log.d("count=" + ratingBar.getRating());
                        if (ratingBar.getRating() > 0) {

                            dao.judge(kcid, ratingBar.getRating() + "", CodeConst.COURSE_GET_COURSE_JUDGE_SUBMIT);
                            materialDialog.dismiss();
                        } else {
                            MessageUtils.showImageShortToast(context, "请选择评分");
                        }
                    }
                })
                .negativeText(R.string.disagree)
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
                        materialDialog.dismiss();
                    }
                })
                .negativeColorRes(R.color.color_999)
                .autoDismiss(false).show();
    }

    public void loadmore(List<JRCourse> list) {
        courseList.addAll(list);
        notifyDataSetChanged();

    }

    public void refresh(List<JRCourse> list) {
        clear(courseList);
        courseList.addAll(list);
        notifyDataSetChanged();
    }

    @Override
    public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
        return null;
    }

    @Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int position) {

    }

    @Override
    public void onRequestSuccess(int requestCode) {
        switch (requestCode) {
            case CodeConst.COURSE_GET_COURSE_JUDGE_SUBMIT://提交课程评价
                //评价成功，更新课程信息
                courseList.get(pjPostion).setIsJudge(3);
                notifyDataSetChanged();
                MessageUtils.showRightImageShortToast(context,"评价成功");
//                holder.pj.setClickable(false);
//                judge_text.setText("已评价");
//                courseInfo.setIsJudge(1);
//                //刷新课程详情信息
//                showCourseInfo();

                break;
        }
    }

    @Override
    public void onRequestFaild(int requestCode, String errorNo, String errorMessage) {

    }

    @Override
    public void onNoConnect() {

    }

    @Override
    public void onInvalidLogin() {

    }

    public class ViewHolder extends UltimateRecyclerviewViewHolder {
        ImageView kcfm;//课程封面
        TextView kcmc;// 课程名称
        TextView updateTime;//上次学习时间
//        TextView kczs;//课程总的章节
        TextView kcjd;//课程目前学习的章节
//        ProgressBar progressBar;// 进度
        RelativeLayout ao;//点击区域
        View line;//底部分割线
        TextView pj;//评价

        public ViewHolder(View itemView, boolean isItem) {
            super(itemView);
            if (isItem) {
                //控件布局
                kcfm = (ImageView) itemView.findViewById(R.id.kcfm);// 课程封面
                kcmc = (TextView) itemView.findViewById(R.id.kcmc);//课程名称
                updateTime = (TextView) itemView.findViewById(R.id.update_time);// 上次学习时间
//                progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);//进度条
//                kczs = (TextView) itemView.findViewById(R.id.kczs);//课程总的章节
                kcjd = (TextView) itemView.findViewById(R.id.kcjd);//课程目前学习的章节
                ao = (RelativeLayout) itemView.findViewById(R.id.ao);//点击区域
                line = itemView.findViewById(R.id.line);
                pj = (TextView) itemView.findViewById(R.id.my_jr_pj);
            }
        }
    }
}
